package com.wondertek.poms.core.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.core.service.IChannelInfoPackageService;
import com.wondertek.poms.core.service.IChannelPackageService;
import com.wondertek.poms.dao.po.ChannelInfoPackage;
import com.wondertek.poms.dao.po.ChannelPackage;
import com.wondertek.poms.dao.pojo.ChannelPackagePojo;
import com.wondertek.poms.dao.repo.IChannelPackageDao;
import com.wondertek.poms.dao.vo.ChannelPackageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;

@Service
public class ChannelPackageServiceImpl extends ServiceImpl<ChannelPackage,Long> implements IChannelPackageService {

	@PersistenceContext
    public EntityManager entityManager;
    @Autowired
    private IChannelInfoPackageService channelInfoPackageService;
    @Autowired
    private IChannelPackageService channelPackageService;
    @Autowired
    private IChannelPackageDao channelPackageDao;


    @Override
    public Page<ChannelPackage> findAll(ChannelPackagePojo entity, int page, int rows, String sord, String sidx) {
        StringBuilder condition = sqlStringWhere(entity,sord,sidx);
        Object o = entityManager
                .createNativeQuery("select count(*) from ( " + condition.toString() + " ) a").getSingleResult();
        int count = Convert.toInt(o);
        Pageable pageable = getPageable(page - 1, rows, sord, sidx);

        if(count>0){
            Query query=entityManager.createNativeQuery(condition.toString(), ChannelPackage.class);
            query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            query.setMaxResults(pageable.getPageSize());
            List<ChannelPackage> list=query.getResultList();
            PageImpl<ChannelPackage> result=new PageImpl<>(list,pageable,count);
            entityManager.close();
            return result;
        }
        entityManager.close();
        return Page.empty(pageable);
    }

    @Override
    @Transactional
    public void deleteByPackageId(Long packageId) {
        channelPackageService.deleteById(packageId);
        channelInfoPackageService.deleteByPackageId(packageId);
    }

    @Override
    public List<String> getAllPackageNames() {
        return channelPackageDao.getAllPackageNames();
    }

    @Override
    public List<ChannelPackage> findAllByIsPublish() {
        return channelPackageDao.findAllByIsPublish(1);
    }

    @Override
    public List<ChannelPackageVo> findForSelect() {
        //数据量很少 凑合用一下
        String sql = "select cp.ID,cp.NAME,cp.PROPERTY,cp.DETAIL,WMSYS.WM_CONCAT(ci.ID)  from CHANNEL_PACKAGE cp"+
                " left join CHANNEL_INFO_PACKAGE ci on cp.id=ci.CHANNEL_PACKAGE_ID"+
                " where cp.IS_PUBLISH=1"+
                " group by  cp.ID,cp.NAME,cp.PROPERTY,cp.DETAIL";
        Query query=entityManager.createNativeQuery(sql);
        List<Object[]> list=query.getResultList();
        if(list==null || list.size()==0){
            return new ArrayList<>();
        }
        List<ChannelPackageVo> list0=new ArrayList<>();
        for (Object[] objs:list) {
            ChannelPackageVo channelPackageVo=new ChannelPackageVo();
            channelPackageVo.setId(StringUtil.nullToLong(objs[0]));
            channelPackageVo.setName(StringUtil.nullToString(objs[1]));
            channelPackageVo.setProperty(StringUtil.nullToInteger(objs[2]));
            channelPackageVo.setDetail(StringUtil.nullToString(objs[3]));
            channelPackageVo.setCipIds(StringUtil.nullToString(objs[4]));
            list0.add(channelPackageVo);
        }
        return list0;
    }

    @Override
    public Map<String, Object> getChannelPackageMap() {
        List<ChannelPackage> cps = channelPackageDao.findAllByIsPublish(1);
        Map<Long, List<String>> cipsM = new HashMap<Long, List<String>>();
        if(cps!=null && cps.size()>0) {
            for(ChannelPackage cp: cps) {
                List<String> chs;
                if(cipsM.containsKey(cp.getId())) {
                    chs = (List<String>)cipsM.get(cp.getId());
                }else {
                    chs = new ArrayList<String>();
                }
                List<ChannelInfoPackage> cips = this.channelInfoPackageService.findAllByPackageId(cp.getId());
                if(cips!=null&&cips.size()>0) {
                    for(ChannelInfoPackage cip:cips) {
                        chs.add(cip.getChannelId());
                    }
                }

                cipsM.put(cp.getId(), chs);
            }
        }
        List<Map<String, Object>> rstL = new ArrayList<Map<String, Object>>();
        if(cipsM.size()>0) {
            Iterator<Long> itr = cipsM.keySet().iterator();
            while(itr.hasNext()) {
                Map<String, Object> rstM = new HashMap<String, Object>();
                Long id = itr.next();
                rstM.put("id", id);
                rstM.put("channels", cipsM.get(id));

                rstL.add(rstM);
            }
        }
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("channelPkgs", rstL);
        Map<String, Object> metaMap = new HashMap<String, Object>();
        metaMap.put("CHANNEL", root);
        return metaMap;
    }

    public StringBuilder sqlStringWhere(ChannelPackagePojo entity, String sord, String sidx) {
        StringBuilder condition = new StringBuilder();
        String sql = "select * from CHANNEL_PACKAGE where 1=1 ";
        condition.append(sql);

        if (entity.getId() != null) {
            condition.append("and ID= " + entity.getId() + " ");
        }
        if (StrUtil.isNotBlank(entity.getName())) {
            condition.append("and NAME like '%"+entity.getName()+"%' ");
        }
        if(entity.getIsPublish() != null){
            condition.append("and IS_PUBLISH = "+entity.getIsPublish()+" ");
        }
        if(StrUtil.isNotBlank(entity.getChannelId())){
            List<ChannelInfoPackage> list=channelInfoPackageService.findAllByChannelId(entity.getChannelId());
            String packageIds="";
            if(list != null && list.size()>0){
                for(ChannelInfoPackage channelInfoPackage:list){
                    packageIds+=","+channelInfoPackage.getChannelPackageId();
                }
                packageIds=packageIds.substring(1);
            }
            condition.append("and ID in ("+packageIds+") " );
        }
        condition.append("order by "+sidx+" "+sord);
        return condition;
    }

    @Override
    public ChannelPackage deleteLogic(Long id) {
        return null;
    }

    @Override
    public ChannelPackage merge(ChannelPackage model) {
        return null;
    }


}
